﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace LambdaToSql.EntityModel.SqLite
{
    [Serializable]
    [DataContract]
    internal class QueryEntity<T> : LambdaToSql.EntityModel.QueryEntity<T> where T : class, new()
    {
        public QueryEntity(LambdaToSql.EntityModel.DbContext context) : base(context)
        {

        }

        #region GetStr

        /// <summary>
        /// 最终查询字符串 只读
        /// </summary>
        [DataMember]
        public override string SqlStr
        {
            get
            {
                var sql = "";
                if (!string.IsNullOrEmpty(this.GroupByStr))
                {
                    sql = string.Format(SqlTemplate, this.FieldsStr, this.TableName + " " + this.WhereStr + " " + this.GroupByStr + " " + this.TopStr);
                }
                else
                {
                    sql = string.Format(SqlTemplate, this.FieldsStr, this.TableName + " " + this.WhereStr + " " + this.OrderByStr + " " + this.TopStr);
                }
                return sql;
            }
        }

        /// <summary>
        /// 函数最终查询字符串 只读
        /// </summary>
        [DataMember]
        public override string SqlFunStr
        {
            get
            {
                var sql = string.Format(SqlTemplate, this.FieldsStr, this.TableName + " " + this.WhereStr);
                if (!string.IsNullOrEmpty(this.TopStr))
                {
                    sql = string.Format(SqlTemplate, this.FieldsStr, this.TableName + " " + this.WhereStr + " " + this.OrderByStr + " " + this.TopStr);
                }
                return sql;
            }
        }
        #endregion

        #region Sql Template

        /// <summary>
        /// top N模板
        /// </summary>
        [DataMember]
        public override string TopTemplate
        {
            get
            {
                return "limit {0}";
            }
        }

        /// <summary>
        /// top N模板
        /// </summary>
        [DataMember]
        public override string PageTemplate
        {
            get
            {
                var sql = new StringBuilder();
                sql.Append("select");
                sql.Append(" " + this.FieldsStr);
                sql.Append(" " + "from");
                sql.Append(" " + this.TableName);
                sql.Append(" " + this.WhereStr);
                sql.Append(" " + this.OrderByStr);
                sql.Append(" " + " limit {0} offset {1}");

                var _temp = sql.ToString();
                return _temp;
            }
        }


        #endregion
    }
}
